package com.fzq.web;
import com.fzq.dao.po.ApiResponse;
import com.fzq.service.impl.DockerLibreOfficeService;
import com.fzq.utils.LegacyFilenameEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Files;

@RestController
@RequestMapping("/api/convert")
@CrossOrigin(origins = "*")
public class FileConvertController {

    private static final Logger logger = LoggerFactory.getLogger(FileConvertController.class);

    @Autowired
    private DockerLibreOfficeService converterService;

    /**
     * 文档转换接口
     */
    @PostMapping("/document")
    public ResponseEntity<Resource> convertDocument(
            @RequestParam("file") MultipartFile file,
            @RequestParam("targetFormat") String targetFormat) {

        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body(null);
        }

        File convertedFile = null;
        try {
            // 执行转换
            convertedFile = converterService.convertDocument(file, targetFormat.toLowerCase());

            // 设置下载文件名
            String originalFilename = file.getOriginalFilename();
            String downloadFilename = originalFilename != null ?
                    originalFilename.replaceFirst("\\.[^\\.]+$", "") + "." + targetFormat :
                    "converted." + targetFormat;

            // 准备文件资源
            Resource resource = new FileSystemResource(convertedFile);

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, LegacyFilenameEncoder.encodeFilename(downloadFilename))
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .contentLength(convertedFile.length())
                    .body(resource);

        } catch (Exception e) {
            logger.error("文档转换失败", e);
            return ResponseEntity.status(500).build();
        } finally {
            // 异步清理临时文件
            if (convertedFile != null && convertedFile.exists()) {
                File finalConvertedFile = convertedFile;
                new Thread(() -> {
                    try {
                        Thread.sleep(30000); // 30秒后清理，确保下载完成
                        Files.deleteIfExists(finalConvertedFile.toPath());
                        logger.info("已清理临时文件: {}", finalConvertedFile.getName());
                    } catch (Exception e) {
                        logger.warn("清理临时文件失败: {}", finalConvertedFile.getName(), e);
                    }
                }).start();
            }
        }
    }

    /**
     * 获取支持的转换格式
     */
    @GetMapping("/supported-formats")
    public ApiResponse getSupportedFormats() {
        try {
            return ApiResponse.success(converterService.getSupportedConversions());
        } catch (Exception e) {
            return ApiResponse.error("获取支持格式失败: " + e.getMessage());
        }
    }

    /**
     * 检查服务状态
     */
    @GetMapping("/status")
    public ApiResponse getServiceStatus() {
        try {
            Object statusInfo = converterService.getServiceStatus();
            return ApiResponse.success("服务状态检查完成", statusInfo);
        } catch (Exception e) {
            return ApiResponse.error("服务状态检查失败: " + e.getMessage());
        }
    }

    /**
     * 健康检查接口
     */
    @GetMapping("/health")
    public ApiResponse healthCheck() {
        return ApiResponse.success("服务正常运行", new Object() {
            public final String status = "UP";
            public final String timestamp = java.time.LocalDateTime.now().toString();
        });
    }
}